package cn.quevo.ucenter.client.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.HandlerInterceptor;

import cn.quevo.core.entity.UserInfoDetails;
import cn.quevo.core.exception.CustomException;
import cn.quevo.core.exception.NotLoginException;
import cn.quevo.core.lang.StringUtils;
import cn.quevo.spring.util.WebUtils;
import cn.quevo.ucenter.client.service.ClientRestService;
import cn.quevo.ucenter.client.util.ClientUserUtil;
import cn.quevo.ucenter.core.OAuthContext;

public abstract class AbstractAuthorizedHandlerInterceptor<T extends UserInfoDetails> implements HandlerInterceptor {

    /**
     * 必须注入一个clientRestService实现
     */
    private ClientRestService clientRestService;

    public AbstractAuthorizedHandlerInterceptor(ClientRestService clientRestService) {
        this.clientRestService = clientRestService;
    }

    protected ClientRestService getClientRestService() {
        return this.clientRestService;
    }

    /**
     * 获取用户信息
     * 
     * @author July july_sky@foxmail.com
     * @date 2018年3月28日 下午4:42:48
     * @param request
     * @throws CustomException
     */
    protected UserInfoDetails getUserInfo(HttpServletRequest request) throws CustomException {
        UserInfoDetails clientUser = ClientUserUtil.getLoginUser();
        if (clientUser == null) {
            String token = request.getParameter(OAuthContext.OAUTH_ACCESS_TOKEN);
            if (StringUtils.isBlank(token)) {
                token = WebUtils.getSessionOrCookie(OAuthContext.OAUTH_ACCESS_TOKEN);
            }
            if (StringUtils.isBlank(token)) {
                throw new NotLoginException();
            }
            clientUser = this.clientRestService.getUserByToken(token);
            if (StringUtils.isBlank(token)) {
                throw new NotLoginException();
            }
            ClientUserUtil.setLoginUser(clientUser);
        }
        return clientUser;
    }
}
